<template>
	<view class="container">

		<u-sticky :offset-top="navbarHeight">
			<view class="sticky_container">
				<view class="date">
					<view class="now-date">
						<span class="f44 bold">{{ nowDay }}</span>
						<span class="f32 bold ml10">{{ nowMonth }}月</span>
					</view>
					<!-- <view class="select-date" @click="handleSelectDate"> -->
					<view class="select-date">
						<div class="f32 bold">{{ nowYear }}</div>
					</view>
				</view>
			</view>
		</u-sticky>
		<view class="data-list">
			<view class="cell-handler" v-for="(item, index) in evaluateList" :key="index" :data-time="item.createTime">
				<view class="observe-cell">
					<view class="left-content">
						<span class="day">{{ item.nowDay }}</span>
						<span class="month">{{ item.nowMonth }}月</span>
					</view>
					<view class="right-content">
						<view class="wrap-content"
							:class="{spring:item.season==1,summer:item.season==2,autumn:item.season==3,winter:item.season==4}">
							<view class="mark"
								:class="{spring:item.season==1,summer:item.season==2,autumn:item.season==3,winter:item.season==4}">
							</view>

							<view class="f28">
								<!-- 学期信息 -->
								<view
									style="font-size: 28rpx; color: #3A3D4B;line-height: 40rpx; font-family: PingFangSC, PingFang SC;">
									{{formatDate(item.startTime)}}-{{formatDate(item.endTime)}}
								</view>
								<!-- 观察文字 -->
								<view
									style="margin-top: 10rpx; font-size: 28rpx; line-height: 40rpx; color: #3A3D4B;width: calc(100vw - 220rpx); word-wrap: break-word; ">
									{{ item.content }}
								</view>
								<!-- 观察图片或者视频 -->
								<view class="image" v-if="item.imagesList != null && item.imagesList.length <= 1">
									<view v-for="(imgs,imgIdx) in item.imagesList">
										<video v-if="isVideoUrl(imgs.url)" :src="imgs.url"></video>
										<image v-else :src="imgs.url" mode="aspectFill" :key="imgIdx"
											@click="lookImg([item.imagesList,imgIdx])" />
									</view>
								</view>
								<view class="image" v-else-if="item.imagesList != null && item.imagesList.length > 1">
									<uni-grid :column="3" :showBorder="false">
										<uni-grid-item v-for="(ele, row) in item.imagesList">
											<view class="" style="padding: 2px;;height: 100%;width: 100%;">
												<image style="width: 100%; height: 100%;" mode="aspectFill"
													:src="ele.url" @click="lookImg([item.imagesList, row])">
												</image>
											</view>
										</uni-grid-item>
									</uni-grid>
								</view>
							</view>
							<view style="margin: 10rpx 0rpx;  display: flex; align-items: center;">
								<span class="f24 time">{{ formatDate(item.createTime) }}</span>
								<!-- <span class="delete" @click="handleDelete(item.id, index)"
									style="display: flex; align-items: center;">
									<image class="icon-delete"></image>
								</span>
								<span class="edit" @click="handleEditObserve(item)"
									style="display: flex; align-items: center;">
									<image class="icon-edit"></image>
								</span> -->
							</view>

							<view class="item-content" v-if="item.fileUrl" @click="copyBtn(item)">
								<view class="icon-word icon">
								</view>
								<view class="title">学期评价文件:</view>
								<view class="right-content">
									<view class="text">{{item.fileUrl}}</view>
									<image class="icon-copy icon">
									</image>
								</view>
							</view>
						</view>

					</view>

				</view>
			</view>
		</view>
		<!-- 删除确认弹窗 -->
		<rf-alert :show="confirmShow" @close="confirmShow=false" @confirm="confirm" title="提示"
			desc="确认删除该评价?"></rf-alert>

		<!-- 筛选时间 -->
		<view class="popup">
			<u-datetime-picker ref="myElement" :show="selectDateShow" v-model="dateDaya" mode="year-month"
				confirmColor="#58C866" @cancel="selectDateShow = false" title="选择日期"
				v-on:confirm="confirmDate"></u-datetime-picker>
		</view>
	</view>
</template>

<script>
	import {
		getEvaluateList,
		deleteEvaluate,
	} from "@/api/eval.js"

	import {
		zip,
		Observable,
		Subject
	} from 'rxjs'

	// 创建两个主题
	const confirmSub = new Subject();
	const changeSub = new Subject();

	export default {
		name: "view-share-evaluate",
		props: {
			evaluateList: {
				type: Array,
				required: true,
				default: []
			},
		},
		data() {
			return {

				dataList: [],

				nowMonth: '',
				nowDay: '',
				nowYear: '',

				params: {
					pageSize: 10,
					pageNum: 1,
					year: '',
					month: '',
					childId: this.childid,
				},

				total: 0,
				status: "",

				confirmShow: false,
				dateDaya: Number(new Date()), // 时间筛选默认值
				selectDateShow: false,

				delId: "",
				delIndex: "",

				is_load: true,
			};
		},
		computed: {
			navbarHeight() {
				return parseInt(this.navBarHeight, 10) + uni.upx2px(429) + 'px';
			}
		},
		created() {

			let that = this
			// zip(confirmSub, changeSub).subscribe(([val1, val2]) => {
			// 	console.log('收到值:', uni.$u.timeFormat(val2.value, 'yyyy mm'));

			// 	that.params.year = uni.$u.timeFormat(val2.value, 'yyyy')
			// 	that.params.month = uni.$u.timeFormat(val2.value, 'mm')

			// 	that.nowMonth = that.params.month;
			// 	that.nowYear = that.params.year;

			// 	that.params.pageNum = 1

			// 	// 
			// 	this._getEvaluateList()

			// });


			this._getEvaluateList();
		},
		methods: {
			// 判断地址是否为视频地址
			isVideoUrl(url) {
				// 视频常见后缀名列表
				const videoExtensions = ['mp4', 'flv', 'avi', 'wmv', 'mov', 'mkv', 'rm', 'rmvb'];

				// 获取url的最后一部分（通常为文件名+后缀）
				const fileName = url.split('/').pop();

				// 分离出文件后缀名
				const fileExtension = fileName.split('.').pop().toLowerCase();

				// 判断后缀名是否在视频格式列表中
				return videoExtensions.includes(fileExtension);
			},
			formatDate(dataStr) {
				const date = new Date(dataStr);
				if (!isNaN(date)) {
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');
					return `${year}年${month}月${day}日`;
					// return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
				} else {
					// 无法解析日期，返回原始字符串或抛出错误，取决于需求
					return dataStr;
				}
			},
			// 预览图片
			lookImg: function(val) {
				const urls = val[0].map(item => {
					return item.url
				})
				const current = val[1]
				console.log(urls);
				console.log(current);

				uni.previewImage({
					urls,
					current
				})
			},
			copyBtn(item) {
				let _that = this;
				wx.setClipboardData({
					//复制文本
					data: item.fileUrl,
					success: function(res) {
						wx.showToast({
							title: '复制成功',
							icon: 'none',
							mask: 'true' //是否设置点击蒙版，防止点击穿透
						});
					}
				});
			},
			formatArray(arr) {
				return arr.map(item => {
					const date = new Date(item.createTime);
					// const year = date.getFullYear();
					// const month = String(date.getMonth() + 1).padStart(2, '0');
					// const day = String(date.getDate()).padStart(2, '0');
					item.nowMonth = date.getMonth() + 1
					item.nowDay = date.getDate()

					return item
				})
			},
			_getEvaluateList() {
				let _that = this;
				console.log("_getEvaluateList");
				getEvaluateList(this.params).then(res => {
					console.log(JSON.stringify(res));

					if (res.data.code == 200) {

						var list = res.data.rows ? res.data.rows : []
						console.log("_that.dataList", res);
						_that.total = res.data.total
						if (_that.params.pageNum == 1) {
							_that.dataList = _that.formatArray(list)
						} else {
							_that.dataList = _that.dataList.concat(_that.formatArray(list))
						}
						console.log("list=================");
						console.log(list);
						console.log(_that.params.pageSize);
						if (list.length < _that.params.pageSize) {
							_that.status = 'noMore';
						} else {
							console.log("-------------------");
							_that.status = 'more';
						}
					}
				})
			},
			handleSelectDate() {
				// 显示时间筛选
				this.selectDateShow = true;
			},
			// 选定日期， 筛选观察
			confirmDate(e) {

				// 
				this.selectDateShow = false

				this.year = uni.$u.timeFormat(e.value, 'yyyy')
				this.month = uni.$u.timeFormat(e.value, 'mm')

				// 筛选显示的日期
				this.nowYear = this.year
				this.nowMonth = this.month

				// 筛选的参数
				this.params.pageNum = "1"
				this.params.year = this.year
				this.params.month = this.month



				this._getEvaluateList()
			},
			changeDate(e) {
				changeSub.next(e)
			},

			// 删除观察
			handleDelete(id, idx) {
				let _that = this
				console.log(id, idx);
				this.delId = id;
				this.delIndex = idx;
				this.confirmShow = true
			},
			// 删除
			confirm() {
				console.log(this.delId, this.delIndex);
				let _that = this
				deleteEvaluate(this.delId).then(res => {
					console.log(res);
					console.log("res: " + JSON.stringify(res));
					if (res.code == 200) {
						_that.is_load = false
						_that.dataList.splice(_that.delIndex, 1)
						_that.confirmShow = false;
						_that._getEvaluateList()
					}
				}).catch(err => {

				})
			},
			handleEditObserve(item) {
				console.log("itemitem: " + JSON.stringify(item));
				uni.navigateTo({
					url: '/pages-sub/addEval/addEval?type=update&item=' + encodeURIComponent(JSON.stringify(item))
				})

			},
			// 初始化日期
			initTime() {
				const time = new Date();
				//获得系统年份;
				const year = time.getFullYear();
				//获得系统月份;
				const month = time.getMonth() + 1;
				//获得系统当月分天数;
				const day = time.getDate();
				//获得系统星期几;
				let dayCycle = time.getDay();
				//使用数组更改日期样式;
				const dayCycleArray = ["日", "一", "二", "三", "四", "五", "六"];
				for (let i = 0; i < 7; i++) {
					if (dayCycle == i) {
						//将dayCycleArray的数赋值到系统星期几里面中去;
						dayCycle = dayCycleArray[i];
					}
				}
				this.dateStr = year + '/' + month + '/' + day + ' ';
				this.week = '星期' + dayCycle;
				this.nowMonth = month;
				this.nowDay = day;
				this.nowYear = year;
			},

			onClickedDocTime() {
				// 全部学期
				this.selectDateShow = false
				this.nowYear = "全部学期"

				this.params.pageNum = "1"
				this.params.year = ""

				this._getEvaluateList()
			},
		},
		mounted() {
			this.initTime();
			let _that = this;
			let topOffset = parseInt(this.navBarHeight, 10) + uni.upx2px(429)
			uni.$on('onPageScroll', function(data) {
				if (_that.dataList.length > 0) {
					const query = uni.createSelectorQuery().in(_that);
					query.selectAll('.cell-handler').boundingClientRect(data => {
						for (let index = 0; index < data.length; index++) {
							if (data[index].top > topOffset && data[index].top < (topOffset + 100)) {
								let temp = data[index].dataset.time.split(' ')[0].split('-')
								_that.nowDay = temp[2]
								_that.nowMonth = temp[1]
								_that.nowYear = temp[0]
								break
							};
						}
					}).exec();

				}

			});

			uni.$on('onReachBottom', function() {

				if (_that.is_load == false) {
					_that.is_load = true
					return
				}

				if (_that.dataList.length >= _that.total) {
					_that.status = 'noMore';
				} else {
					_that.status = 'more';
					_that.params.pageNum++
					_that._getEvaluateList()
				}

			});

			uni.$on('onShow', function() {

				_that.params.pageNum = 1;
				_that._getEvaluateList()
			});

			uni.$on('RefreshEvalList', function() {
				// 创建或者编辑学期评价后刷新
				_that.params.pageNum = 1;
				_that._getEvaluateList()
			});


		},
		beforeDestroy() {
			uni.$off('onPageScroll')
			uni.$off('onReachBottom')
			uni.$off('onShow')
			uni.$off('RefreshEvalList')
		}

	}
</script>


<style lang="scss" scoped>
	.container {
		background-color: #FFF;

		.sticky_container {
			padding: 10rpx 0 0 0;
			background-color: #FFF;

			.date {
				background-color: white;
				height: 80rpx;
				padding: 0 32rpx;
				display: flex;
				justify-content: space-between;
				align-items: flex-end;

				.now-date {
					// margin-top: 32rpx;
					// flex: 1;
				}

				.select-date {
					// margin-top: 32rpx;
					position: relative;
					padding-right: 45rpx;
					// flex: 1;

					&:before {
						content: '';
						width: 0;
						height: 0;
						position: absolute;
						right: 0;
						top: 15rpx;
						border-top: 15rpx solid #3A3D4B;
						border-left: 15rpx solid transparent;
						border-right: 15rpx solid transparent;
					}
				}
			}
		}

		.data-list {
			padding: 20rpx;


			.observe-cell {
				display: flex;
				margin: 30rpx 0;


				.left-content {
					flex-grow: 1;
					padding: 10rpx 0 0 10rpx;

					.day {
						font-size: 28px;
					}

					.month {
						margin-left: 10rpx;
						font-size: 18px;
					}
				}

				.right-content {
					flex: 1;

					.wrap-content {
						// background-color: #F7F9FA;
						padding: 20rpx;

						border-radius: 10rpx;
						position: relative;
						width: calc(100vw - 170rpx);

						.content {
							margin-top: 10rpx;
							font-size: 28rpx;
							line-height: 40rpx;
							color: #3A3D4B;
							width: calc(100vw - 200rpx);
							word-wrap: break-word;
						}

						&.spring {
							background-color: #F0FCF2;
						}

						&.summer {
							background-color: #F0FCF2;
						}

						&.autumn {
							background-color: #FFFAEE;
						}

						&.winter {
							background-color: #F0FCF2;
						}

						.mark {
							width: 138rpx;
							height: 50rpx;
							position: absolute;
							right: 20rpx;
							top: -8rpx;
							background-size: cover;
							background-repeat: no-repeat;
							background-position: center center;

							&.spring {
								background-image: url("");
							}

							&.summer {
								background-image: url("");
							}

							&.autumn {
								background-image: url("");
							}

							&.winter {
								background-image: url("");
							}

						}



						.right-content {
							display: flex;
							justify-content: flex-start;
							align-items: center;
							flex: 1;

							.text {
								flex: 1;
								text-align: left;
								margin-left: 10rpx;

								max-width: 250rpx;
								white-space: nowrap;
								text-overflow: ellipsis;
								overflow: hidden;
							}

							.icon {

								width: 30rpx;
								height: 30rpx;
								margin: 0rpx 20rpx;
							}


						}

						.delete {
							margin-left: 30rpx;
							cursor: pointer;

							image {
								width: 30rpx;
								height: 30rpx;
							}
						}

						.edit {
							margin-left: 50rpx;
							cursor: pointer;

							image {
								width: 30rpx;
								height: 30rpx;
							}
						}

						.item-content {
							display: flex;
							align-items: center;
							margin-top: 20rpx;

							.icon {
								width: 30rpx;
								height: 30rpx;
								margin-right: 10rpx;

							}

							.title {
								white-space: nowrap;
							}

							.right-content {
								display: flex;
								justify-content: space-between;
								align-items: center;

								.text {
									flex-grow: 1;
									text-align: left;
									white-space: nowrap;
									text-overflow: ellipsis;
									overflow: hidden;
								}

								.icon {
									width: 30rpx;
									height: 30rpx;
									margin: 0rpx 10rpx;
								}
							}
						}
					}
				}
			}

		}

		.popup {
			.u-popup__content {
				position: relative;
				border-radius: 24rpx 24rpx 0 0;
				overflow: hidden;
				padding-bottom: 150rpx;
			}

			.u-picker__view {
				height: 360rpx !important;
			}


			.u-toolbar__wrapper__cancel {
				padding: 0;
				position: absolute;
				left: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.u-toolbar__wrapper__confirm {
				padding: 0;
				position: absolute;
				right: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.picker-view {
			width: 100%;
			height: 400rpx;
			margin-top: 20rpx;
		}

		.item {
			line-height: 100rpx;
			text-align: center;
			font-size: 20pt;
		}

		.picker-btn {
			display: flex;
			margin-top: 40rpx;
			margin-bottom: 40rpx;

			.btn {
				flex: 1;
				width: 200rpx;
				height: 72rpx;
				// color: #58C866;
				// background: #FFFFFF;
				// border-radius: 36rpx;
				// border: 2rpx solid #58C866;
				text-align: center;
				line-height: 72rpx;
				margin: 0 10rpx;
			}

			.confirm {
				color: #58C866;
				// color: #fff;
			}
		}


	}
</style>